package com.lagou.rpc.consumer.client;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

public class RpcClientProxy {
    public static Object creatProxy(Class serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameters(args);
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        RpcClient client = new RpcClient("localhost");
                        Object send = client.send(JSON.toJSONString(rpcRequest));
                        RpcResponse rpcResponse = JSON.parseObject(send.toString(), RpcResponse.class);
                        if(rpcResponse.getError()!= null){
                            throw  new Exception(rpcResponse.getError());
                        }
                        Object result = rpcResponse.getResult();


                        return  JSON.parseObject(result.toString(), method.getReturnType());
                    }
                }

        );
    }
}
